import 'package:flutter/material.dart';
import 'package:flutter_give/pages/auth/login_page.dart';
import 'package:flutter_give/route/route_utils.dart';
import 'package:flutter_give/route/routes.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:flutter_give/utils/constants.dart';
import 'package:flutter_give/utils/sp_utils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

import 'GuidePage.dart';
import 'http/dio_instance.dart';

/// 适配方法
Size get designSize {
  final firstView = WidgetsBinding.instance.platformDispatcher.views.first;
  // 逻辑短边
  final logicalShortestSide =
      firstView.physicalSize.shortestSide / firstView.devicePixelRatio;
  // 逻辑长边
  final logicalLongestSide =
      firstView.physicalSize.longestSide / firstView.devicePixelRatio;
  // 缩放比例 designSize越小，元素越大
  const scaleFactor = 0.95;
  // 缩放后的逻辑短边和长边
  return Size(
      logicalShortestSide * scaleFactor, logicalLongestSide * scaleFactor);
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<StatefulWidget> createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 配置请求-
    // DioInstance.instance().initDio(baseUrl: "http://jxjzw.zhgdyun.com:11024");
    _init();
  }

  void _init() async {
    // showToast("===========init初始化方法===========");
    // 犀云实例化文件
    // RinoSDK.event.userLogoutStream.listen((event) {
    //   WidgetsBinding.instance.addPostFrameCallback((_) {
    //     LogUtils.w("用户已退出，token失效或已在别处登录等");
    //     showToast("============用户已退出，token失效或已在别处登录等==============");
    //   });
    //   // showToast("============1==============");
    //   // 重置
    //   GlobalData.store.dispatch(LoggoutAction());
    // });
    // GlobalData.store.dispatch(initSdk());
  }

  Future<bool> initData() async {
    bool shouldLogin = false;
    await SpUtils.getString(Constants.SP_USER_NAME).then((value) {
      // showToast("用户名${value}");
      if (value == null || value == "") {
        shouldLogin = true;
        // showToast("用户名${value}去登录页");
      } else {
        shouldLogin = false;
        // showToast("用户名${value}去登录页");
      }
    });
    return shouldLogin;
  }

  @override
  Widget build(BuildContext context) {

    return OKToast(
      child: ScreenUtilInit(
        designSize: designSize,
        child: FutureBuilder(
          future: initData(),
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.done) {
              bool shouldLogin = snapshot.data ?? false;
              // 移除 StoreProvider 和 GlobalData.store
              return MaterialApp(
                title: 'Flutter Demo',
                // 去除角标
                debugShowCheckedModeBanner: false,
                // 主题适配文件
                theme: ThemeData(
                  // 主题色
                  colorScheme:
                  ColorScheme.fromSeed(seedColor: Color(0xFF26b2f3)),

                  // 主题色 - 会导致组件样式丢失
                  // colorScheme: const ColorScheme.light(
                  //     primary: Colors.white,
                  //     onPrimary: Colors.white,
                  //     onBackground: Colors.white,
                  //     secondary: Colors.white),
                  useMaterial3: true,
                  // 修改滚动时候背景色不会叠加
                  appBarTheme: const AppBarTheme(
                    surfaceTintColor: Colors.transparent,
                  ),
                ),
                // 挂载页面实例
                navigatorKey: RouteUtils.navigatorKey,
                routes: {
                  '/login': (context) => LoginPage(),
                  // 其他路由
                },
                // 挂载路由
                onGenerateRoute: Routes.generateRoute,
                // 第一个页面-页面入口
                // initialRoute:
                //     shouldLogin ? RoutePath.loginPage : RoutePath.tab,
                home: GuidePage(),
                // 配置
                localizationsDelegates: [
                  // Material 组件的本地化文本
                  GlobalMaterialLocalizations.delegate,
                  // 提供基础 Widgets 的本地化文本
                  GlobalWidgetsLocalizations.delegate,
                  // 提供 Cupertino 风格的本地化文本
                  GlobalCupertinoLocalizations.delegate,
                ],
                supportedLocales: [
                  // 初始化组件-语言
                  const Locale('zh', 'CH'),
                  const Locale('en', 'US'),
                ],
              );
            } else {
              // 显示加载中的UI，例如一个CircularProgressIndicator
              // return Center(child: CircularProgressIndicator());
              // 使用零尺寸盒子
              return SizedBox.shrink();
              // 显示加载中的UI，例如一个CircularProgressIndicator
            }
          },
        ),
      ),
    );
  }
}
